<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rust代码闯关 - 拖拽学习</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
            overflow-x: hidden;
        }

        /* 动态背景粒子 */
        .floating-shapes {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 0;
        }

        .shape {
            position: absolute;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
            animation: float 15s infinite linear;
        }

        .shape:nth-child(1) { width: 80px; height: 80px; left: 10%; animation-delay: 0s; }
        .shape:nth-child(2) { width: 120px; height: 120px; left: 20%; animation-delay: 2s; }
        .shape:nth-child(3) { width: 60px; height: 60px; left: 70%; animation-delay: 4s; }
        .shape:nth-child(4) { width: 100px; height: 100px; left: 80%; animation-delay: 6s; }

        @keyframes float {
            0% { transform: translateY(100vh) rotate(0deg); opacity: 0; }
            10% { opacity: 1; }
            90% { opacity: 1; }
            100% { transform: translateY(-100px) rotate(360deg); opacity: 0; }
        }

        /* 顶部导航栏 */
        .top-nav {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
            z-index: 1000;
            padding: 15px 0;
        }

        .nav-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .logo {
            font-size: 1.5rem;
            font-weight: bold;
            background: linear-gradient(135deg, #667eea, #764ba2);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .progress-badge {
            background: linear-gradient(135deg, #4facfe, #00f2fe);
            color: white;
            padding: 8px 15px;
            border-radius: 20px;
            font-size: 0.9rem;
            font-weight: 600;
        }

        /* 主容器 */
        .main-container {
            margin-top: 80px;
            max-width: 1400px;
            margin: 80px auto 0;
            padding: 20px;
            position: relative;
            z-index: 1;
        }

        /* 关卡选择视图 */
        .level-selector {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            backdrop-filter: blur(20px);
        }

        .section-title {
            font-size: 2rem;
            font-weight: 700;
            text-align: center;
            margin-bottom: 10px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .section-subtitle {
            text-align: center;
            color: #666;
            margin-bottom: 30px;
            font-size: 1.1rem;
        }

        /* 主题关卡网格 */
        .topic-levels {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 25px;
            margin-bottom: 40px;
        }

        .topic-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            transition: all 0.3s ease;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .topic-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 35px rgba(0,0,0,0.15);
        }

        .topic-header {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }

        .topic-icon {
            width: 60px;
            height: 60px;
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.8rem;
            margin-right: 15px;
        }

        .topic-ownership { background: linear-gradient(135deg, #ff6b6b, #ee5a52); }
        .topic-borrowing { background: linear-gradient(135deg, #4ecdc4, #44a08d); }
        .topic-lifetimes { background: linear-gradient(135deg, #f093fb, #f5576c); }
        .topic-traits { background: linear-gradient(135deg, #4facfe, #00f2fe); }
        .topic-error-handling { background: linear-gradient(135deg, #fa709a, #fee140); }
        .topic-closures { background: linear-gradient(135deg, #30cfd0, #330867); }
        .topic-concurrency { background: linear-gradient(135deg, #a8edea, #fed6e3); }
        .topic-macros { background: linear-gradient(135deg, #ff9a9e, #fecfef); }
        .topic-pattern-matching { background: linear-gradient(135deg, #ffecd2, #fcb69f); }
        .topic-iterators { background: linear-gradient(135deg, #a1c4fd, #c2e9fb); }

        .topic-info h3 {
            font-size: 1.4rem;
            margin-bottom: 5px;
            color: #333;
        }

        .topic-info p {
            color: #666;
            font-size: 0.9rem;
        }

        .levels-preview {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .level-dot {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.9rem;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .level-dot.completed {
            background: linear-gradient(135deg, #00b894, #00a085);
            color: white;
        }

        .level-dot.current {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            animation: pulse 2s infinite;
        }

        .level-dot.locked {
            background: #f1f3f4;
            color: #9aa0a6;
        }

        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.1); }
        }

        /* 挑战游戏视图 */
        .challenge-view {
            display: none;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            backdrop-filter: blur(20px);
        }

        .challenge-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
        }

        .challenge-title {
            font-size: 1.8rem;
            font-weight: 700;
            color: #333;
        }

        .back-button {
            background: #f8f9fa;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: all 0.3s ease;
        }

        .back-button:hover {
            background: #e9ecef;
            transform: translateX(-2px);
        }

        .challenge-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-bottom: 30px;
        }

        .code-section {
            background: #1e1e1e;
            border-radius: 15px;
            padding: 25px;
            color: #d4d4d4;
            font-family: 'Consolas', 'Monaco', monospace;
            position: relative;
            overflow: hidden;
        }

        .code-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 5px;
            background: linear-gradient(90deg, #667eea, #764ba2);
        }

        .code-title {
            color: #4ecdc4;
            font-weight: 600;
            margin-bottom: 20px;
            font-size: 1rem;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .code-template {
            margin-bottom: 20px;
        }

        .code-line {
            padding: 8px 0;
            position: relative;
            transition: all 0.2s ease;
        }

        .code-line:hover {
            background: rgba(255, 255, 255, 0.05);
        }

        .code-line-number {
            color: #858585;
            margin-right: 15px;
            font-size: 0.9rem;
            user-select: none;
        }

        .blank-spot {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 6px 12px;
            border-radius: 6px;
            cursor: pointer;
            display: inline-block;
            min-width: 120px;
            text-align: center;
            transition: all 0.3s ease;
            position: relative;
            font-weight: 500;
        }

        .blank-spot.filled {
            background: linear-gradient(135deg, #00b894, #00a085);
        }

        .blank-spot.drag-over {
            background: linear-gradient(135deg, #ff6b6b, #ee5a52);
            transform: scale(1.05);
        }

        .code-fragments {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 25px;
            position: relative;
            overflow: hidden;
        }

        .code-fragments::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 5px;
            background: linear-gradient(90deg, #4ecdc4, #44a08d);
        }

        .fragments-title {
            color: #333;
            font-weight: 600;
            margin-bottom: 20px;
            font-size: 1rem;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .fragment-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
            max-height: 400px;
            overflow-y: auto;
            padding-right: 10px;
        }

        .fragment-item {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 15px;
            cursor: grab;
            transition: all 0.3s ease;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 0.95rem;
            position: relative;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }

        .fragment-item:hover {
            border-color: #667eea;
            transform: translateY(-3px);
            box-shadow: 0 6px 15px rgba(102, 126, 234, 0.15);
        }

        .fragment-item.dragging {
            opacity: 0.5;
            transform: rotate(5deg);
            cursor: grabbing;
        }

        .fragment-item.used {
            opacity: 0.3;
            cursor: not-allowed;
            background: #f1f3f4;
        }

        .controls {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-top: 30px;
        }

        .btn {
            padding: 12px 30px;
            border: none;
            border-radius: 10px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-transform: uppercase;
            letter-spacing: 1px;
            position: relative;
            overflow: hidden;
        }

        .btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.2);
            transition: left 0.3s ease;
        }

        .btn:hover::before {
            left: 100%;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
        }

        .btn-secondary {
            background: #f8f9fa;
            color: #333;
        }

        .btn-secondary:hover {
            background: #e9ecef;
        }

        .btn-success {
            background: linear-gradient(135deg, #00b894, #00a085);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(0, 184, 148, 0.3);
        }

        /* 结果模态框 */
        .result-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.8);
            z-index: 2000;
            backdrop-filter: blur(5px);
        }

        /* .result-content styles moved to external CSS to avoid conflicts */

        .result-icon {
            font-size: 4rem;
            margin-bottom: 20px;
            animation: bounce 1s ease;
        }

        @keyframes bounce {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.2); }
        }

        .result-title {
            font-size: 1.8rem;
            font-weight: 700;
            margin-bottom: 15px;
        }

        .result-message {
            color: #666;
            margin-bottom: 30px;
            line-height: 1.6;
        }

        .explanation {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            margin-top: 20px;
            text-align: left;
        }

        .explanation h4 {
            color: #333;
            margin-bottom: 10px;
        }

        /* 进度条 */
        .progress-bar {
            height: 8px;
            background: #e9ecef;
            border-radius: 4px;
            overflow: hidden;
            margin-bottom: 20px;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            transition: width 0.5s ease;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .challenge-content {
                grid-template-columns: 1fr;
                gap: 20px;
            }
            
            .topic-levels {
                grid-template-columns: 1fr;
            }
            
            .main-container {
                padding: 15px;
            }
        }

        /* 拖拽相关样式 - 确保与外部CSS不冲突 */
        .fragment-item {
            cursor: grab !important;
            user-select: none !important;
            -webkit-user-select: none !important;
            -moz-user-select: none !important;
            -ms-user-select: none !important;
        }
        
        .fragment-item.dragging {
            opacity: 0.6 !important;
            transform: rotate(5deg) !important;
            cursor: grabbing !important;
        }
        
        .blank-spot {
            min-height: 24px !important;
            min-width: 80px !important;
            display: inline-block !important;
        }
        
        .blank-spot.drag-over {
            background: rgba(206, 66, 43, 0.2) !important;
            border-color: #ff6b35 !important;
        }
    </style>
</head>
<body>
    <!-- 动态背景 -->
    <div class="floating-shapes">
        <div class="shape"></div>
        <div class="shape"></div>
        <div class="shape"></div>
        <div class="shape"></div>
    </div>

    <!-- 顶部导航 -->
    <div class="top-nav">
        <div class="nav-content">
            <div class="logo">🚀 Rust 代码闯关</div>
            <div class="user-info">
                <div class="progress-badge" id="userProgress">0/10 完成</div>
            </div>
        </div>
    </div>

    <!-- 主容器 -->
    <div class="main-container">
        <!-- 关卡选择视图 -->
        <div class="level-selector" id="levelSelector">
            <h1 class="section-title">选择你的挑战</h1>
            <p class="section-subtitle">通过拖拽代码片段来学习 Rust 的核心概念</p>
            
            <div class="progress-bar">
                <div class="progress-fill" id="progressFill" style="width: 0%"></div>
            </div>
            
            <div class="topic-levels" id="topicLevels">
                <!-- 主题关卡将动态生成 -->
            </div>
        </div>

        <!-- 挑战游戏视图 -->
        <div class="challenge-view" id="challengeView">
            <div class="challenge-header">
                <h2 class="challenge-title" id="challengeTitle">挑战标题</h2>
                <button class="back-button" onclick="showLevelSelector()">← 返回关卡</button>
            </div>
            
            <div class="challenge-content">
                <div class="code-section">
                    <div class="code-title">代码模板</div>
                    <div class="code-template" id="codeTemplate">
                        <!-- 代码模板将动态生成 -->
                    </div>
                </div>
                
                <div class="code-fragments">
                    <div class="fragments-title">代码片段</div>
                    <div class="fragment-list" id="fragmentList">
                        <!-- 代码片段将动态生成 -->
                    </div>
                </div>
            </div>
            
            <div class="controls">
                <button class="btn btn-secondary" onclick="resetChallenge()">重置</button>
                <button class="btn btn-primary" onclick="checkAnswer()">检查答案</button>
                <button class="btn btn-success" onclick="nextLevel()" id="nextLevelBtn" style="display: none;">下一关 →</button>
            </div>
        </div>
    </div>

    <!-- 结果模态框 -->
    <div class="result-modal" id="resultModal">
        <div class="result-content">
            <div class="result-icon" id="resultIcon">🎉</div>
            <h3 class="result-title" id="resultTitle">恭喜通过！</h3>
            <p class="result-message" id="resultMessage">你成功完成了这个挑战！</p>
            <div class="explanation" id="explanation" style="display: none;">
                <h4>💡 解释</h4>
                <p id="explanationText"></p>
            </div>
            <div class="controls">
                <button class="btn btn-secondary" onclick="closeResult()">关闭</button>
                <button class="btn btn-primary" onclick="nextLevelFromModal()" id="modalNextBtn" style="display: none;">下一关 →</button>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentChallenge = null;
        let currentLevelIndex = 0;
        let currentTopic = null;
        let userProgress = {};
        let challengesData = null;
        let completedChallenges = [];

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadChallenges();
        });

        // 加载挑战数据
        async function loadChallenges() {
            try {
                const response = await fetch('/api/challenges?user_id=web_user');
                const data = await response.json();
                challengesData = data.challenges;
                updateUserProgress();
                renderTopicLevels();
            } catch (error) {
                console.error('Failed to load challenges:', error);
            }
        }

        // 更新用户进度
        function updateUserProgress() {
            if (!challengesData) return;
            
            const totalChallenges = Object.values(challengesData).reduce((total, topic) => total + topic.levels.length, 0);
            const completedCount = completedChallenges.length;
            const progressPercentage = totalChallenges > 0 ? (completedCount / totalChallenges) * 100 : 0;
            
            document.getElementById('userProgress').textContent = `${completedCount}/${totalChallenges} 完成`;
            document.getElementById('progressFill').style.width = `${progressPercentage}%`;
        }

        // 渲染主题关卡
        function renderTopicLevels() {
            const container = document.getElementById('topicLevels');
            container.innerHTML = '';

            if (!challengesData) return;

            Object.entries(challengesData).forEach(([topicId, topicData]) => {
                const card = createTopicCard(topicId, topicData);
                container.appendChild(card);
            });
        }

        // 创建主题卡片
        function createTopicCard(topicId, topicData) {
            const card = document.createElement('div');
            card.className = 'topic-card';
            card.onclick = () => enterTopic(topicId);

            // 根据主题ID获取对应的样式类
            const iconClass = `topic-${topicId}`;
            const icon = getTopicIcon(topicId);

            const levelsHtml = topicData.levels.map((level, index) => {
                const status = getLevelStatus(topicId, index);
                return `<div class="level-dot ${status}">${index + 1}</div>`;
            }).join('');

            card.innerHTML = `
                <div class="topic-header">
                    <div class="topic-icon ${iconClass}">${icon}</div>
                    <div class="topic-info">
                        <h3>${topicData.title}</h3>
                        <p>${topicData.description}</p>
                    </div>
                </div>
                <div class="levels-preview">
                    ${levelsHtml}
                </div>
            `;

            return card;
        }

        // 获取主题图标
        function getTopicIcon(topicId) {
            const icons = {
                'ownership': '🔑',
                'borrowing': '🔗',
                'lifetimes': '⏳',
                'traits': '🎭',
                'error-handling': '⚠️',
                'closures': '📦',
                'concurrency': '🚀',
                'macros': '🔧',
                'pattern-matching': '🎯',
                'iterators': '🔄'
            };
            return icons[topicId] || '📚';
        }

        // 获取关卡状态
        function getLevelStatus(topicId, levelIndex) {
            const challengeId = `${topicId}_${levelIndex + 1}`;
            if (completedChallenges.includes(challengeId)) {
                return 'completed';
            }
            // 如果是第一个关卡或者是前一个关卡已完成
            if (levelIndex === 0 || completedChallenges.includes(`${topicId}_${levelIndex}`)) {
                return 'current';
            }
            return 'locked';
        }

        // 进入主题
        function enterTopic(topicId) {
            currentTopic = topicId;
            currentLevelIndex = 0;
            
            // 找到第一个未完成的关卡
            const topic = challengesData[topicId];
            for (let i = 0; i < topic.levels.length; i++) {
                const challengeId = `${topicId}_${i + 1}`;
                if (!completedChallenges.includes(challengeId)) {
                    currentLevelIndex = i;
                    break;
                }
            }
            
            loadChallenge();
        }

        // 加载挑战
        async function loadChallenge() {
            if (!challengesData || !currentTopic) return;

            const topic = challengesData[currentTopic];
            const level = topic.levels[currentLevelIndex];

            if (!level) return;

            currentChallenge = level;

            // 更新UI
            document.getElementById('challengeTitle').textContent = level.title;
            document.getElementById('levelSelector').style.display = 'none';
            document.getElementById('challengeView').style.display = 'block';

            // 渲染代码模板
            renderCodeTemplate(level.code_template);
            renderFragments(level.code_fragments);
        }

        // 渲染代码模板
        function renderCodeTemplate(template) {
            const container = document.getElementById('codeTemplate');
            container.innerHTML = '';

            template.forEach((line, index) => {
                const lineDiv = document.createElement('div');
                lineDiv.className = 'code-line';
                
                // 检查是否有空白处
                const hasBlank = line.includes('_____');
                
                if (hasBlank) {
                    const parts = line.split('_____');
                    lineDiv.innerHTML = `
                        <span class="code-line-number">${index + 1}</span>
                        ${parts[0]}
                        <span class="blank-spot" data-position="0" ondrop="dropFragment(event)" ondragover="allowDrop(event)" ondragleave="removeDragOver(event)">拖拽代码</span>
                        ${parts[1] || ''}
                    `;
                } else {
                    lineDiv.innerHTML = `
                        <span class="code-line-number">${index + 1}</span>
                        ${line}
                    `;
                }
                
                container.appendChild(lineDiv);
            });
        }

        // 渲染代码片段
        function renderFragments(fragments) {
            const container = document.getElementById('fragmentList');
            container.innerHTML = '';

            fragments.forEach(fragment => {
                const fragmentDiv = document.createElement('div');
                fragmentDiv.className = 'fragment-item';
                fragmentDiv.draggable = true;
                fragmentDiv.textContent = fragment.code;
                fragmentDiv.dataset.id = fragment.id;
                fragmentDiv.dataset.correct = fragment.correct;
                fragmentDiv.dataset.hint = fragment.hint;

                fragmentDiv.ondragstart = (e) => {
                    e.dataTransfer.setData('text/plain', fragment.code);
                    e.dataTransfer.setData('text/fragmentId', fragment.id);
                    fragmentDiv.classList.add('dragging');
                };

                fragmentDiv.ondragend = () => {
                    fragmentDiv.classList.remove('dragging');
                };

                container.appendChild(fragmentDiv);
            });
        }

        // 拖拽处理
        function allowDrop(e) {
            e.preventDefault();
            e.stopPropagation();
            if (e.target.classList.contains('blank-spot')) {
                e.target.classList.add('drag-over');
            }
        }

        function removeDragOver(e) {
            e.preventDefault();
            e.stopPropagation();
            if (e.target.classList.contains('blank-spot')) {
                e.target.classList.remove('drag-over');
            }
        }

        function dropFragment(e) {
            e.preventDefault();
            e.stopPropagation();
            
            if (!e.target.classList.contains('blank-spot')) {
                return;
            }
            
            e.target.classList.remove('drag-over');
            
            const code = e.dataTransfer.getData('text/plain');
            const fragmentId = e.dataTransfer.getData('text/fragmentId');
            
            // 如果目标位置已有内容，先清空
            if (e.target.textContent !== '拖拽代码') {
                // 找到之前使用的片段并重新启用
                const oldFragmentId = e.target.dataset.fragmentId;
                if (oldFragmentId) {
                    const oldFragment = document.querySelector(`[data-id="${oldFragmentId}"]`);
                    if (oldFragment) {
                        oldFragment.classList.remove('used');
                        oldFragment.draggable = true;
                    }
                }
            }
            
            e.target.textContent = code;
            e.target.dataset.fragmentId = fragmentId;
            e.target.classList.add('filled');
            
            // 禁用已使用的片段
            const fragmentItem = document.querySelector(`[data-id="${fragmentId}"]`);
            if (fragmentItem) {
                fragmentItem.classList.add('used');
                fragmentItem.draggable = false;
            }
        }

        // 检查答案
        function checkAnswer() {
            if (!currentChallenge) return;

            const blanks = document.querySelectorAll('.blank-spot.filled');
            const answers = Array.from(blanks).map(blank => blank.textContent.trim());
            const correctAnswers = currentChallenge.correct_answer;

            // 检查答案是否正确
            const isCorrect = JSON.stringify(answers.sort()) === JSON.stringify(correctAnswers.sort());

            if (isCorrect) {
                // 标记当前挑战为已完成
                const challengeId = `${currentTopic}_${currentLevelIndex + 1}`;
                if (!completedChallenges.includes(challengeId)) {
                    completedChallenges.push(challengeId);
                    updateUserProgress();
                }
                
                showResult(true, currentChallenge.explanation);
            } else {
                showResult(false);
            }
        }

        // 显示结果
        function showResult(isCorrect, explanation = '') {
            const modal = document.getElementById('resultModal');
            const icon = document.getElementById('resultIcon');
            const title = document.getElementById('resultTitle');
            const message = document.getElementById('resultMessage');
            const explanationDiv = document.getElementById('explanation');
            const explanationText = document.getElementById('explanationText');
            const nextBtn = document.getElementById('modalNextBtn');

            if (isCorrect) {
                icon.textContent = '🎉';
                title.textContent = '恭喜通过！';
                message.textContent = '你成功完成了这个挑战！';
                explanationDiv.style.display = explanation ? 'block' : 'none';
                if (explanation) {
                    explanationText.textContent = explanation;
                }
                nextBtn.style.display = 'block';
            } else {
                icon.textContent = '😔';
                title.textContent = '再试一次！';
                message.textContent = '答案不正确，看看提示再试试吧！';
                explanationDiv.style.display = 'none';
                nextBtn.style.display = 'none';
            }

            modal.style.display = 'block';
        }

        // 关闭结果模态框
        function closeResult() {
            document.getElementById('resultModal').style.display = 'none';
        }

        // 下一关
        function nextLevel() {
            if (!challengesData || !currentTopic) return;

            const topic = challengesData[currentTopic];
            if (currentLevelIndex < topic.levels.length - 1) {
                currentLevelIndex++;
                loadChallenge();
            } else {
                showLevelSelector();
            }
        }

        function nextLevelFromModal() {
            closeResult();
            nextLevel();
        }

        // 重置挑战
        function resetChallenge() {
            if (!currentChallenge) return;

            // 清除所有填充的空白
            const blanks = document.querySelectorAll('.blank-spot.filled');
            blanks.forEach(blank => {
                // 找到之前使用的片段并重新启用
                const oldFragmentId = blank.dataset.fragmentId;
                if (oldFragmentId) {
                    const oldFragment = document.querySelector(`[data-id="${oldFragmentId}"]`);
                    if (oldFragment) {
                        oldFragment.classList.remove('used');
                        oldFragment.draggable = true;
                    }
                }
                
                blank.textContent = '拖拽代码';
                blank.classList.remove('filled');
                delete blank.dataset.fragmentId;
            });

            // 确保所有片段都可用
            const fragments = document.querySelectorAll('.fragment-item');
            fragments.forEach(fragment => {
                fragment.classList.remove('used');
                fragment.draggable = true;
            });
        }

        // 返回关卡选择
        function showLevelSelector() {
            document.getElementById('challengeView').style.display = 'none';
            document.getElementById('levelSelector').style.display = 'block';
            currentChallenge = null;
            renderTopicLevels(); // 重新渲染以更新状态
        }

        // 点击模态框外部关闭
        document.getElementById('resultModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeResult();
            }
        });
    </script>
</body>
</html>